from fastapi import APIRouter, HTTPException, status, Depends
from typing import List, Optional
from pydantic import BaseModel
from app.services.example_service import example_service, ExampleItem

import aio_pika
import json
router = APIRouter()

class Task(BaseModel):
    message: str
async def get_rabbit_connection():
    connection = await aio_pika.connect_robust("amqp://free2walk:free2walk@192.168.25.202:5672//")
    yield connection
    await connection.close()

@router.post("/rabbitmq_demo")
async def rabbitmq_demo(task: Task, connection=Depends(get_rabbit_connection)):
    """获取所有项目"""
    channel = await connection.channel()
    exchange = await channel.declare_exchange("main_exchange", "topic")
    await exchange.publish(
        aio_pika.Message(body=json.dumps(task.model_dump()).encode(), delivery_mode=2),
        routing_key="task_queue"
    )
    return {"status": "Task enqueued"}